package com.bgs.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.ObjectMetadata;
import com.bgs.pojo.AliOssEntity;
import com.bgs.service.AliOssService;
import org.joda.time.DateTime;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.UUID;

/**
 * @author Asia
 * @version 1.0
 * @description: TODO
 * @date 2021/8/17 11:18
 */
@Service
public class AliOssServiceImpl implements AliOssService, InitializingBean{
    @Autowired
    private AliOssEntity aliOssEntity;

    private String endpoint;
    private String accessKeyId;
    private String accessKeySecret;
    private String bucketName;

    @Override
    public void afterPropertiesSet() throws Exception {
        endpoint = aliOssEntity.getEndpoint();
        accessKeyId = aliOssEntity.getAccessKeyId();
        accessKeySecret = aliOssEntity.getAccessKeySecret();
        bucketName = aliOssEntity.getBucketName();
    }

    @Override
    public void createBucket() {
        // 创建OSSClient实例
        OSS ossClient = new OSSClientBuilder()
                .build(endpoint, accessKeyId, accessKeySecret);
        if (ossClient.doesBucketExist(bucketName)) {
            throw new RuntimeException(bucketName + "在对象存储的bucket列表中已存在");
        }
        // 创建存储空间
        ossClient.createBucket(bucketName);
        // 关闭
        ossClient.shutdown();
    }

    @Override
    public String upload(MultipartFile file) {
        OSS ossClient = new OSSClientBuilder()
                .build(endpoint, accessKeyId, accessKeySecret);
        try {
            //获取上传文件输入流
            InputStream inputStream = file.getInputStream();
            //获取文件名称
            String originName = file.getOriginalFilename();

            //1 在文件名称里面添加随机唯一的值
            String fileName = UUID.randomUUID().toString().replaceAll("-", "");

            String fileType = originName.substring(originName.lastIndexOf("."));

            String newName = fileName + fileType;

            //2 把文件按照日期进行分类
            //获取当前日期 2019/11/12
            String datePath = new DateTime().toString("yyyy/MM/dd");
            //拼接
            fileName = datePath + "/" + newName;

            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setObjectAcl(CannedAccessControlList.PublicRead);
            objectMetadata.setContentType(getcontentType(fileType));

            //调用oss方法实现上传
            //第一个参数  Bucket名称
            //第二个参数  上传到oss文件路径和文件名称   aa/bb/1.jpg
            //第三个参数  上传文件输入流
            ossClient.putObject(bucketName, fileName, inputStream, objectMetadata);
            // 默认十年不过期
            Date date = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 10);
            String url = ossClient.generatePresignedUrl(bucketName, fileName, date).toString();
            //把上传之后文件路径返回
            return url.substring(0, url.indexOf("?"));
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }finally {
            ossClient.shutdown();
        }
    }

    @Override
    public void download(String fileName) throws IOException {

    }

    @Override
    public void listFile() {

    }

    @Override
    public void deleteFile(String fileName) {

    }

    /**
     * Description: 判断OSS服务文件上传时文件的contentType
     *
     * @return String
     */
    public static String getcontentType(String filenameExtension) {
        if (filenameExtension.equalsIgnoreCase(".bmp")) {
            return "image/bmp";
        }
        if (filenameExtension.equalsIgnoreCase(".gif")) {
            return "image/gif";
        }
        if (filenameExtension.equalsIgnoreCase(".jpg")) {
            return "image/jpg";
        }
        if (filenameExtension.equalsIgnoreCase(".jpeg")) {
            return "image/jpeg";
        }
        if (filenameExtension.equalsIgnoreCase(".html")) {
            return "text/html";
        }
        if (filenameExtension.equalsIgnoreCase(".png")) {
            return "image/png";
        }
        if (filenameExtension.equalsIgnoreCase(".txt")) {
            return "text/plain";
        }
        if (filenameExtension.equalsIgnoreCase(".vsd")) {
            return "application/vnd.visio";
        }
        if (filenameExtension.equalsIgnoreCase(".pptx") || filenameExtension.equalsIgnoreCase(".ppt")) {
            return "application/vnd.ms-powerpoint";
        }
        if (filenameExtension.equalsIgnoreCase(".docx") || filenameExtension.equalsIgnoreCase(".doc")) {
            return "application/msword";
        }
        if (filenameExtension.equalsIgnoreCase(".xml")) {
            return "text/xml";
        }
        return "image/jpeg";
    }
}
